package concurrentprogrammingchat.chat;

import concurrentprogrammingchat.tupleserver.TupleProxy;

public class ChatListener {
	//Theses strings are used as the first field of each tuple do identify what kind of tuple we are dealing with.	
	//There are 4 types of Tuples you can add to or get from Tuple Space.
	public static String MSG = "MESSAGE";
	public static String CN = "CHANNELS_NAMES";
	public static String TI = "TUPLESPACE_INFO";
    public static String LASTID = "LASTID";
	
	private final TupleProxy tupleProxy;
	private final String channel;
	private final int rows;
	private int tupleID;
	
	public ChatListener(TupleProxy tp, String channel)
	{
		tupleProxy = tp;
		this.channel = channel;
		//When the Listener is created, it has to print the rows last message. 
		//So we need "rows" and the last message tuple ID
		//Here we get the Tuple Info from the Tuple Server, in order to get the rows value.
    	String[] tupleInfo = {TI, String.valueOf(tupleProxy.getTupleSpaceID()), null, null};
    	tupleInfo = tupleProxy.get(tupleInfo);
    	rows = Integer.parseInt(tupleInfo[3]);
        String[] result = {LASTID, this.channel, null};
        result = tupleProxy.get(result);
        //Now we initialize the TupleID value 
		this.tupleID = Integer.parseInt(result[2]) - rows;
        if(tupleID<0){
            tupleID = 0;
        }
        
        //Don't forget to put back
        tupleProxy.put(result);
    	tupleProxy.put(tupleInfo);
         
	}
	
	//this method is in a while loop :
	//=> gets the last messages from the value of TupleID
    public String getNextMessage() {
    	//this method is very basic : it returns the message and increment the tupleID
    		String[] result = {MSG, channel, String.valueOf(tupleID + 1), null};
    		result = tupleProxy.get(result);
    		tupleID ++;
    		//Don't forget to put back
    		tupleProxy.put(result);
    		return result[3];
    }

    //We don't have to do anything while closing a listener because our implementation of listener does not modify anything and there is no storage of listeners.
    public void closeConnection() {    	
    }
}
